package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import com.tanhua.model.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public Map login(String username, String password, String verificationCode, String uuid) {
        //判断用户名或者密码是否为空
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw  new BusinessException("用户名或者密码不能为空");
        }
        //判断验证码是正确
        if(StringUtils.isEmpty(verificationCode)){
            throw new BusinessException(ErrorResult.loginError().getErrMessage());
        }
        String key =Constants.SMS_CODE+uuid;
        String code = redisTemplate.opsForValue().get(key);
        if(!code.equals(verificationCode)){
            throw new BusinessException(ErrorResult.loginError().getErrMessage());
        }
        //删除redis
        redisTemplate.delete(key);
        //4、根据用户名查询用户
        LambdaQueryWrapper<Admin> lqw =new LambdaQueryWrapper<>();
        lqw.eq(Admin::getUsername,username);
        Admin admin = adminMapper.selectOne(lqw);
        String md5Password = SecureUtil.md5(password);
        //5、判断用户是否存在，密码是否一致
        if(!md5Password.equals(admin.getPassword())){
            //用户名错误或者密码不一致
            throw new BusinessException("密码错误，请重试");
        }
        //6、通过JWT生成token	存用户名和id
        Map<String,Object> claims=new HashMap<>();
        claims.put("username",username);
        claims.put("id",admin.getId());
        String token = JwtUtils.getToken(claims);
        //8、构造返回值
        Map res = new HashMap();
        res.put("token", token);
        return  res;
    }
    //获得用户
    public AdminVo findByAdmin() {
        Long userId = AdminHolder.getUserId();
        LambdaQueryWrapper<Admin> lqw =new LambdaQueryWrapper<>();
        lqw.eq(Admin::getId,userId);
        Admin admin = adminMapper.selectOne(lqw);
        AdminVo init = AdminVo.init(admin);
        return init;
    }
}
